package logic_app_member

import (
	"APT/internal/dao"
	"APT/internal/library/contexts"
	"APT/internal/library/hgorm/hook"
	"APT/internal/library/translate"
	"APT/internal/model"
	"APT/internal/model/entity"
	"APT/internal/model/input/input_app_member"
	"APT/internal/model/input/input_basics"
	"APT/internal/service"
	"context"
	"database/sql"
	"errors"
	"fmt"
	"github.com/gogf/gf/v2/container/gvar"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"strings"
	"sync"
)

type TranslateTextRes struct {
	Zh   string `json:"zh" dc:"简体中文翻译结果"`
	ZhCN string `json:"zh_CN" dc:"繁体翻译结果"`
	Ko   string `json:"ko" dc:"韩文翻译结果"`
	Ja   string `json:"ja" dc:"日文翻译结果"`
	En   string `json:"en" dc:"英文翻译结果"`
}

func (s *sAppMember) RegisterMemberAward(ctx context.Context, TX gdb.TX, MemberId int) (err error) {
	var (
		MemberInfo            *entity.PmsMember
		RecommendedMemberInfo *entity.PmsMember
		Recommended           int
		MemberRegRewardConfig *model.MemberRegRewardConfig
		InviteNewRewardConfig *model.InviteNewRewardConfig
		YYConfig              *model.YYConfig
		GIFTContent           string
		couponType            []*entity.PmsCouponType
		WaitGroup             sync.WaitGroup
		translateNitify       *TranslateTextRes
	)

	// 查询用户信息
	if err = dao.PmsMember.Ctx(ctx).TX(TX).WherePri(MemberId).Scan(&MemberInfo); err != nil && !errors.Is(err, sql.ErrNoRows) {
		return
	}
	if g.IsEmpty(MemberInfo) {
		return
	}

	// 新人注册奖励
	if MemberRegRewardConfig, err = service.BasicsConfig().GetMemberRegRewardConfig(ctx); err != nil {
		return
	}
	if MemberRegRewardConfig.IsOpen == 1 {
		// 奖励类型
		RewardTypeArr := strings.Split(MemberRegRewardConfig.RewardType, ",")

		// 开始新人礼奖励
		for _, rewardType := range RewardTypeArr {
			if rewardType == "balance" && MemberRegRewardConfig.RewardBalance > 0 {
				// 奖励积分
				if err = s.MemberBalanceChange(ctx, &input_app_member.MemberBalanceInp{
					MemberId:      MemberId,
					Scene:         "SYSTEM",
					Type:          "AWARD",
					ChangeBalance: MemberRegRewardConfig.RewardBalance,
					OrderSn:       "",
					Des:           "注册奖励",
					MdCode:        MemberInfo.RegisterMdCode,
					MpModel:       MemberInfo.RegisterMpModel,
				}, TX); err != nil {
					return
				}
				GIFTContent += fmt.Sprintf("%d积分,", gvar.New(MemberRegRewardConfig.RewardBalance).Int())
			}
			if rewardType == "coupon" && !g.IsEmpty(MemberRegRewardConfig.CouponTypeIds) {
				// 奖励会员优惠券 source：1-自主领取 2-系统发放 3-注册奖励 4-邀请奖励
				CouponTypeIdsArr := strings.Split(MemberRegRewardConfig.CouponTypeIds, ",")
				if err = dao.PmsCouponType.Ctx(ctx).
					Fields("id,max(coupon_name) as coupon_name,count(id) as count").
					Where(dao.PmsCouponType.Columns().Id, MemberRegRewardConfig.CouponTypeIds).
					Group(dao.PmsCouponType.Columns().Id).
					Hook(hook.PmsFindLanguageValueHook).
					Scan(&couponType); err != nil {
					return
				}
				for _, couponTypeId := range CouponTypeIdsArr {
					if err = service.BasicsCouponType().SendMemberCoupon(ctx, &input_basics.PmsSendMemberCouponInp{
						MemberId:     MemberId,
						CouponTypeId: gvar.New(couponTypeId).Int(),
					}, 3); err != nil {
						return
					}
				}
				for _, v := range couponType {
					GIFTContent += fmt.Sprintf("%sx%d,", v.CouponName, v.Count)
				}
			}
		}
		translateNitify = new(TranslateTextRes)
		WaitGroup.Add(5)
		go func() {
			translateNitify.Zh, err = translate.TranslateText(ctx, GIFTContent, "zh")
			WaitGroup.Done()
		}()
		go func() {
			translateNitify.ZhCN, err = translate.TranslateText(ctx, GIFTContent, "zh_TW")
			WaitGroup.Done()
		}()
		go func() {
			translateNitify.Ko, err = translate.TranslateText(ctx, GIFTContent, "ko")
			WaitGroup.Done()
		}()
		go func() {
			translateNitify.Ja, err = translate.TranslateText(ctx, GIFTContent, "ja")
			WaitGroup.Done()
		}()
		go func() {
			translateNitify.En, err = translate.TranslateText(ctx, GIFTContent, "en")
			WaitGroup.Done()
		}()
		WaitGroup.Wait()
		PmsLanguage := new(entity.PmsLanguage)
		if !g.IsEmpty(GIFTContent) {
			if err = dao.PmsLanguage.Ctx(ctx).Where(g.Map{
				dao.PmsLanguage.Columns().Language: contexts.GetLanguage(ctx),
				dao.PmsLanguage.Columns().Key:      "WELCOME",
			}).Scan(&PmsLanguage); err != nil {
				err = gerror.New("获取语言失败，请稍后重试！")
				return
			}
			err = service.BasicsAppNotify().NotifyEdit(ctx, &input_basics.PmsNotifyEditInp{
				PmsNotify: entity.PmsNotify{
					MemberId:      MemberId,
					NotifyTitle:   "SYSTEM",
					NotifyType:    "GIFT", // 新人礼消息
					NotifyContent: PmsLanguage.Content,
					NotifyData:    gjson.New(translateNitify),
				},
			})
		}
	}
	// 获取推荐制度
	if YYConfig, err = service.BasicsConfig().GetYYConfig(ctx); err != nil {
		return
	}
	// ===邀请注册奖励===
	// 推荐模式
	if YYConfig.RecommendModel == "FIRST" {
		Recommended = MemberInfo.LastReferrer
	} else if YYConfig.RecommendModel == "LAST" {
		Recommended = MemberInfo.Referrer
	} else {
		return
	}
	// 查询推荐人信息
	if err = dao.PmsMember.Ctx(ctx).TX(TX).WherePri(Recommended).Scan(&RecommendedMemberInfo); err != nil && !errors.Is(err, sql.ErrNoRows) {
		return
	}
	if g.IsEmpty(RecommendedMemberInfo) {
		return
	}

	// 邀请注册配置
	if InviteNewRewardConfig, err = service.BasicsConfig().GetInviteNewRewardConfig(ctx); err != nil {
		return
	}

	// 被邀请人奖励
	if InviteNewRewardConfig.IsInviteRegOpen == 1 {
		// 奖励类型
		RewardTypeArr := strings.Split(InviteNewRewardConfig.RewardType, ",")

		for _, rewardType := range RewardTypeArr {
			if rewardType == "balance" && InviteNewRewardConfig.RewardBalance > 0 {
				// 奖励积分
				if err = s.MemberBalanceChange(ctx, &input_app_member.MemberBalanceInp{
					MemberId:      MemberId,
					Scene:         "SYSTEM",
					Type:          "AWARD",
					ChangeBalance: InviteNewRewardConfig.RewardBalance,
					OrderSn:       "",
					Des:           "被邀请注册奖励",
				}, TX); err != nil {
					return
				}

			}
			if rewardType == "coupon" && !g.IsEmpty(InviteNewRewardConfig.CouponTypeIds) {
				// 奖励会员优惠券  source：1-自主领取 2-系统发放 3-注册奖励 4-邀请奖励
				CouponTypeIdsArr := strings.Split(InviteNewRewardConfig.CouponTypeIds, ",")
				for _, couponTypeId := range CouponTypeIdsArr {
					if err = service.BasicsCouponType().SendMemberCoupon(ctx, &input_basics.PmsSendMemberCouponInp{
						MemberId:     MemberId,
						CouponTypeId: gvar.New(couponTypeId).Int(),
					}, 4); err != nil {
						return
					}
				}
			}
		}
	}

	return
}
